﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;
using Newtonsoft.Json.Linq;

namespace LdCms.Web
{
    using LdCms.Common.Extension;
    using LdCms.Common.Json;
    using LdCms.Common.Time;
    using LdCms.Common.Utility;
    using LdCms.EF.DbModels;
    using LdCms.Web.Services;
    using LdCms.Common.Enum;
    using LdCms.Web.Authorizes;
    /// <summary>
    /// 
    /// </summary>
    [AuthFilter]
    [EnableCors("AllowSameDomain")]
    [Route("cgi/v{version:apiVersion}/[controller]/[action]", Name = "[controller]_[action]")]
    [ApiController]
    public class BaseApiController : ControllerBase
    {
        private readonly IBaseApiManager BaseApiManager;
        public BaseApiController(IBaseApiManager BaseApiManager)
        {
            this.BaseApiManager = BaseApiManager;
        }

        protected int SystemID = BaseSystemConfig.SystemID;
        protected int AccessTokenExpiresIn = BaseSystemConfig.AccessTokenExpiresIn;
        protected int RefreshTokenExpiresIn = BaseSystemConfig.RefreshTokenExpiresIn;
        protected string WeChatPayNotifyUrl = BaseSystemConfig.WeChatPayNotifyUrl;
        protected string WeChatPayRefundNotifyUrl = BaseSystemConfig.WeChatPayRefundNotifyUrl;

        protected string AlipayServerCheckUrl = BaseSystemConfig.AlipayServerCheckUrl;
        protected string AlipayTradeNotifyUrl = BaseSystemConfig.AlipayTradeNotifyUrl;


        protected bool IsPermission(string companyId, string staffId, string functionId)
        {
            try
            {
                return BaseApiManager.IsPermission(companyId, staffId, functionId);
            }
            catch (Exception)
            {
                return false;
            }
        }

        private IActionResult ContentResult(string result)
        {
            var contentResult = new ContentResult
            {
                Content = result,
                ContentType = "application/json; charset=utf-8",
                StatusCode = 200
            };
            return contentResult;
        }
        protected virtual IActionResult Result(string data)
        {
            return ContentResult(data);
        }
        protected virtual IActionResult Result(object data)
        {
            string result = data.ToJson();
            return ContentResult(result);
        }
        protected virtual IActionResult Result(long logId, string data)
        {
            BaseApiManager.UpdateLogs(logId, data, true);
            return ContentResult(data);
        }
        protected virtual IActionResult Result(long logId, object data)
        {
            string result = data.ToJson();
            BaseApiManager.UpdateLogs(logId, result, true);
            return ContentResult(result);
        }

        protected virtual IActionResult Success(string message)
        {
            var entity = new { code = (int)ParamEnum.CommonErrorCode.成功, message };
            string result = entity.ToJson();
            return ContentResult(result);
        }
        protected virtual IActionResult Success(string message, object data)
        {
            var entity = new { code = (int)ParamEnum.CommonErrorCode.成功, message, data };
            string result = entity.ToJson();
            return ContentResult(result);
        }
        protected virtual IActionResult Success(long logId, string message)
        {
            var entity = new { code = (int)ParamEnum.CommonErrorCode.成功, message };
            string result = entity.ToJson();
            BaseApiManager.UpdateLogs(logId, result, true);
            return ContentResult(result);
        }
        protected virtual IActionResult Success(long logId, string message, object data)
        {
            var entity = new { code = (int)ParamEnum.CommonErrorCode.成功, message, data };
            string result = entity.ToJson();
            BaseApiManager.UpdateLogs(logId, result, true);
            return ContentResult(result);
        }

        protected virtual IActionResult Error(string message)
        {
            var entity = new { code = (int)ParamEnum.CommonErrorCode.业务处理失败, message };
            string result = entity.ToJson();
            return ContentResult(result);
        }
        protected virtual IActionResult Error(int errCode, string message)
        {
            var entity = new { code = errCode, message };
            string result = entity.ToJson();
            return ContentResult(result);
        }
        protected virtual IActionResult Error(long logId, string message)
        {
            int errCode = (int)ParamEnum.CommonErrorCode.业务处理失败;
            var entity = new { code = errCode, message };
            string result = entity.ToJson();
            BaseApiManager.UpdateLogs(logId, result, true);
            return ContentResult(result);
        }
        protected virtual IActionResult Error(long logId, int errCode, string message)
        {
            var entity = new { code = errCode, message };
            string result = entity.ToJson();
            BaseApiManager.UpdateLogs(logId, result, true);
            return ContentResult(result);
        }

        protected virtual bool IsUuid(string uuid)
        {
            try
            {
                if (string.IsNullOrEmpty(uuid))
                    return false;
                if (uuid.Length != 32)
                    return false;
                return BaseApiManager.IsUuid(uuid);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected virtual bool IsToken(string token)
        {
            try
            {
                if (string.IsNullOrEmpty(token))
                    return false;
                if (token.Length != 128)
                    return false;
                int timestamp = TimeHelper.GetUnixTimestampTen();
                return BaseApiManager.IsToken(token);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected virtual bool IsAccessToken(string accessToken)
        {
            try
            {
                if (string.IsNullOrEmpty(accessToken))
                    return false;
                int timestamp = TimeHelper.GetUnixTimestampTen();
                return BaseApiManager.IsAccessToken(accessToken);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


        protected virtual Ld_Sys_InterfaceAccount GetSysInterfaceAccount(string token)
        {
            try
            {
                return BaseApiManager.GetSysInterfaceAccount(token);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected virtual Ld_Sys_InterfaceAccount GetSysInterfaceAccount(string companyId, string account)
        {
            try
            {
                return BaseApiManager.GetSysInterfaceAccount(companyId, account);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected virtual Ld_Sys_InterfaceAccount GetSysInterfaceAccountByAppId(string appid)
        {
            try
            {
                return BaseApiManager.GetSysInterfaceAccountByAppId(appid);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected virtual Ld_Sys_InterfaceAccount GetSysInterfaceAccountByUuid(string uuid)
        {
            try
            {
                return BaseApiManager.GetSysInterfaceAccountByUuid(uuid);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected virtual Ld_Sys_InterfaceAccount GetSysInterfaceAccountByToken(string token)
        {
            try
            {
                return BaseApiManager.GetSysInterfaceAccountByToken(token);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        protected virtual Ld_Institution_Staff GetInstitutionStaff(string companyId, string staffId)
        {
            try
            {
                return BaseApiManager.GetInstitutionStaff(companyId, staffId);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected virtual Ld_Institution_Staff GetInstitutionStaffByAccessToken(string accessToken)
        {
            try
            {
                return BaseApiManager.GetInstitutionStaffByAccessToken(accessToken);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected virtual Ld_Institution_Staff GetInstitutionStaffByRefreshToken(string refreshToken)
        {
            try
            {
                return BaseApiManager.GetInstitutionStaffByRefreshToken(refreshToken);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


        protected virtual Ld_Member_Account GetMemberAccount(string companyId, string memberId)
        {
            try
            {
                return BaseApiManager.GetMemberAccount(companyId, memberId);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected virtual Ld_Member_Account GetMemberAccountByAccessToken(string accessToken)
        {
            try
            {
                return BaseApiManager.GetMemberAccountByAccessToken(accessToken);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected virtual Ld_Member_Account GetMemberAccountByRefreshToken(string refreshToken)
        {
            try
            {
                return BaseApiManager.GetMemberAccountByRefreshToken(refreshToken);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


        protected virtual string GetQueryString(string name)
        {
            try
            {
                return HttpContext.Request.GetQueryString(name);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected virtual string GetFormValue(string name)
        {
            try
            {
                return HttpContext.Request.GetFormValue(name);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected virtual string GetFormValueArr(string name)
        {
            try
            {
                return HttpContext.Request.GetFormValueArr(name);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected virtual string GetJObjectValue(JObject formValue, string name)
        {
            try
            {
                if (string.IsNullOrEmpty(name))
                    return "";
                if (formValue.Property(name) == null)
                    return "";
                var result = formValue[name];
                if (result == null)
                    return "";
                else
                    return Utility.FilterText(result.ToString().Trim());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected virtual string GetJObjectValueArray(JObject formValue, string name)
        {
            try
            {
                if (string.IsNullOrEmpty(name))
                    return "";
                if (formValue.Property(name) == null)
                    return "";
                var result = formValue[name];
                if (result.Type == JTokenType.Array)
                    return String.Join(",", result);
                return "";
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


        #region 获取接口帐号、会员、员工资料
        protected string Uuid
        {
            get
            {
                return GetQueryString("uuid");
            }
        }
        private string Token
        {
            get
            {
                return GetQueryString("token");
            }
        }
        protected string AccessToken
        {
            get
            {
                return GetQueryString("access_token");
            }
        }
        protected Ld_Sys_InterfaceAccount InterfaceAccount
        {
            get
            {
                string uuid = Uuid;
                string token = Token;
                var interfaceAccount = new Ld_Sys_InterfaceAccount();
                if (string.IsNullOrEmpty(uuid) && string.IsNullOrEmpty(token))
                    throw new Exception("uuid or token not empty！");

                if (!string.IsNullOrEmpty(uuid))
                {
                    if (!IsUuid(uuid))
                        throw new Exception("uuid invalid！");
                    var entity = GetSysInterfaceAccountByUuid(uuid);
                    if (entity == null)
                        throw new Exception("uuid invalid！");
                    interfaceAccount = entity;
                }
                if (!string.IsNullOrEmpty(token))
                {
                    if (!IsToken(token))
                        throw new Exception("token invalid！");
                    var entity = GetSysInterfaceAccountByToken(token);
                    if (entity == null)
                        throw new Exception("uuid invalid！");
                    interfaceAccount = entity;
                }
                return interfaceAccount;
            }
        }
        protected Ld_Institution_Staff InstitutionStaff
        {
            get
            {
                string accessToken = AccessToken;
                if (string.IsNullOrWhiteSpace(accessToken))
                    throw new Exception("access_token not empty！");
                if (!IsAccessToken(accessToken))
                    throw new Exception("access_token invalid！");
                var entity = GetInstitutionStaffByAccessToken(accessToken);
                if (entity == null)
                    throw new Exception("access_token invalid！");
                return entity;
            }
        }
        protected Ld_Member_Account MemberAccount
        {
            get
            {
                string accessToken = AccessToken;
                if (string.IsNullOrWhiteSpace(accessToken))
                    throw new Exception("access_token not empty！");
                if (!IsAccessToken(accessToken))
                    throw new Exception("access_token invalid！");
                var entity = GetMemberAccountByAccessToken(accessToken);
                if (entity == null)
                    throw new Exception("access_token invalid！");
                return entity;
            }
        }
        #endregion


    }
}